<?php

namespace app\api\controller;

use app\admin\model\product\Cart;
use app\admin\model\product\Category;
use app\admin\model\product\Listo;
use app\admin\model\product\Lists;
use app\admin\model\product\Order;
use app\admin\model\product\Sku;
use app\common\controller\Payment;
use think\Db;
use think\Exception;
use think\Request;
use app\common\controller\Api;

class Productorder extends Api
{
    protected static $model = null;
    protected $noNeedLogin = ['logisticsInfo', 'notify'];
    protected $noNeedRight = '*';
    protected static $totalList = 15;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new Order();
    }

    /**
     * 提交订单
     */
    public function createorder()
    {
        if (!request()->isPost()) {
            $this->error('非法操作！');
        }
        $user_id = $this->auth->id;
        $user = \app\admin\model\User::find($user_id);
        $tag = input('tag');
        $message = input('message');
        $reply_image = $this->request->post('reply_image');
        $file_path = $this->request->post('file_path');
        if (!$tag) {
            $this->error('非法操作！');
        }
        if (!$message || !$reply_image) {
            $this->error('参数缺失！');
        }

        $orderInfo = Order::where('orderid', $tag)->find();
        if ($orderInfo) {
            $this->error('重复提交清单');
        }

        $nums = Listo::where('tag', $tag)->count();
        if ($nums <= 0) {
            $this->error('请先选取物资！');
        }

        $data['orderid'] = $tag;//订单号
        $data['user_id'] = $user_id;//当前用户id
//        $data['department_user_id'] = $user->department_user_id;
        $data['message'] = $message;
        $data['reply_image'] = $reply_image;//等待发货
        $data['file_path'] = $file_path;
        $data['status'] = 1;

        Db::startTrans();
        try {
            $odata = self::$model->create($data);
            Listo::where('tag', $tag)->setField('order_id', $odata->id);

            $ndata = [
                'pay_time' => time(),
                'status' => 1
            ];
            Listo::where('order_id', $odata->id)->update($ndata);
            $odata->save($ndata);

            self::updateShop($odata->id);

            Cart::where('user_id', $user_id)->delete();

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success("清单已提交！", [
            'order_num' => $tag
        ]);

    }

    /**
     * 查询订单详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkOrder()
    {
        $orderId = $this->request->post('order_num');
        $oInfo = self::$model->field('id,status')->where('orderid', $orderId)->find();
        if (!$oInfo) {
            $this->error('该订单不存在！');
        }

        $this->success('订单信息', $oInfo);
    }

    /**
     * 更改物资库存
     * @param $orderId
     */
    private function updateShop($orderId)
    {
        $list = Listo::where('order_id', $orderId)->select();
        foreach ($list as $k => $val) {
            Lists::where(array('id' => $val->product_id))->setDec('stock', $val['num']);
        }
    }

    /**
     * 订单列表
     */
    public function lists()
    {
        $pageSize = input('page_size', self::$totalList);
        $status = $this->request->post('status');
        if (!$status) {
            $status = [-1];
        } else {
            $status = explode(',', $status);
        }

        $map = [];
        if (!in_array(-1, $status)) {
            $map['status'] = ['in', $status];
        }

        $user_id = $this->auth->id;

        $orders = self::$model
//            ->field("id,orderid,total,status,paytype,addressid,createtime")
            ->where('user_id', $user_id)
            ->where($map)
            ->order('id desc')
            ->paginate($pageSize)
            ->each(function ($item) {
                $lists = Listo::where('order_id', $item['id'])->select();
                $totalNum = 0;
                if (count($lists) > 0) {
                    foreach ($lists as &$vv) {
                        $pInfo = Lists::where('id', $vv['product_id'])->find();
//                        $vv['product_name'] = $pInfo['product_name'];
//                        $vv['parameter'] = ProductSku::where('id', $vv['parameter_id'])->value('value');

                        $vv['intro'] = $pInfo['intro'];
                        $vv['image'] = make_full_url($pInfo['image']);
                        $totalNum += $vv['num'];
                    }
                }
                $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
                $item['total_num'] = $totalNum;
                $item['product_list'] = $lists;
            });

        $totalCount = self::$model
            ->where('user_id', $user_id)
            ->where($map)
            ->count();

        $this->success('订单列表', ['list' => $orders, 'totalCount' => $totalCount]);
    }

    /**
     * 删除订单
     */
    public function delOrder()
    {
        if (!request()->isPost()) {
            $this->error('非法操作！');
        }

        $id = input('id');
        $orderInfo = self::$model->where('id', $id)->find();
        if (!$orderInfo) {
            $this->error('该订单不存在！');
        }
        if ($orderInfo['status'] != 20) {
            $this->error('该订单不可删除！');
        }

        $res = self::$model->where('id', $id)->update(['status' => -2]);
        if (!$res) {
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }
}